package cn.yeziji.forum.dao.impl;

import cn.yeziji.forum.converter.CommentConverter;
import cn.yeziji.forum.dao.base.ForumUserCommentBaseDao;
import cn.yeziji.forum.dao.intf.ForumUserCommentDao;
import cn.yeziji.forum.dao.iquery.UserCommentQuery;
import cn.yeziji.forum.dto.comment.ForumOperationCommentDTO;
import cn.yeziji.forum.entity.ForumCommentEntity;
import cn.yeziji.forum.entity.ForumUserCommentEntity;
import cn.yeziji.forum.mapper.ForumCommentMapper;
import cn.yeziji.forum.mapper.ForumUserCommentMapper;
import cn.yeziji.forum.utils.JwtOperaUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 用户操作评论逻辑实现类
 *
 * @author gzkemays
 * @since 2021/12/21 15:54
 */
@Repository
public class ForumUserCommentDaoImpl extends ForumUserCommentBaseDao
    implements ForumUserCommentDao {
  @Resource ForumUserCommentMapper userCommentMapper;
  @Resource ForumCommentMapper commentMapper;
  @Resource HttpServletRequest request;
  CommentConverter converter = CommentConverter.INSTANCE;

  @Override
  public int commentToGood(ForumOperationCommentDTO dto) {
    Integer userId = JwtOperaUtils.getUserIdByRequest(request);
    dto.setUserId(userId);
    ForumUserCommentEntity one =
        userCommentMapper.findOne(
            UserCommentQuery.getCommentByCommentIdAndUserId(dto.getCommentId(), userId));
    // 更新评论的数量
    int newGoodNumber;
    ForumCommentEntity comment = commentMapper.findById(dto.getCommentId());
    Integer goodNumber = comment.getGoodNumber();
    // 判断更新还是插入
    if (Objects.isNull(one)) {
      // 插入 userComment
      one = converter.operationCommentConverterEntity(dto);
      userCommentMapper.insert(one);
      // 必然为点赞
      newGoodNumber = goodNumber + 1;
      comment.setGoodNumber(newGoodNumber);
      commentMapper.updateById(comment);
    } else {
      // 更新 userComment
      Boolean toGood = one.getToGood();
      one.setToGood(!toGood);
      userCommentMapper.updateById(one);
      // 计算最新的点赞数量 更新 comment
      newGoodNumber = toGood ? goodNumber + 1 : goodNumber - 1;
      comment.setGoodNumber(newGoodNumber);
      commentMapper.updateById(comment);
    }
    return newGoodNumber;
  }
}
